import 'package:flutter/material.dart';
import '../my_base_lib/base_lib.dart';

class PageViewTestPage extends StatefulWidget {
  static String routeName = "/PageViewTestPage";

  const PageViewTestPage({Key? key}) : super(key: key);

  @override
  _PageViewTestPageState createState() => _PageViewTestPageState();
}

class _PageViewTestPageState extends BaseWidgetState<PageViewTestPage> {
  late PageController _pageController;
  int _index = 0;
  bool onTop = false;

  late ScrollController _page1ScrollController;
  GlobalKey _keyOfSliverAppBar = GlobalKey();

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _index);
    _page1ScrollController = ScrollController();
    _page1ScrollController.addListener(() {
      if(_page1ScrollController.hasClients){
        /*final RenderBox renderBox = _keyOfSliverAppBar.currentContext?.findRenderObject() as RenderBox;
        double h = renderBox.size.height;
        LogUtils.e("==$h",tag: "滑动时获取到高度");*/
        setState(() {
          //onTop = (h==80);
          onTop=_page1ScrollController.offset >= 320.0;
        });
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          //centerTitle: true,
          title: const Text("PageView demo"),
        ),
        body: Column(
          children: [
            Expanded(
              child: PageView(
                physics: const NeverScrollableScrollPhysics(), //设置page不响应滑动
                controller: _pageController,
                onPageChanged: (index) {
                  setState(() {
                    _index = index;
                  });
                },
                children: _getItemViews(),
              ),
            ),
            _getBottomViews()
          ],
        ));
  }



  _getItemViews() {
    return [
      Container(
        color: Colors.amber,
        child: NestedScrollView(
            controller: _page1ScrollController,
            headerSliverBuilder: (context, innerBoxIsScrolled) {
              return <Widget>[
                SliverAppBar(
                  key: _keyOfSliverAppBar,
                  automaticallyImplyLeading: false,
                  pinned: true,
                  floating: true,
                  expandedHeight: 400,
                  flexibleSpace: FlexibleSpaceBar(

                    collapseMode: CollapseMode.pin,
                    background: Container(
                      height: 400,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage("assets/image/gjc.png"),
                              fit: BoxFit.fill)),
                      alignment: Alignment.center,
                      child: Text(
                        '我来组成头部',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    ),
                  ),
                  bottom: PreferredSize(
                      child: Container(
                        height: 80,
                        color: Colors.blue,
                        alignment: Alignment.center,
                        child: Text(
                          '我是自定义悬浮部分${onTop?"我在顶上":"我不在顶上"}',
                          style: TextStyle(color: Colors.white, fontSize: 20),
                        ),
                      ),
                      preferredSize: const Size(double.infinity, 80)),
                ),
              ];
            },
            body: _getListView()),
      ),
      Container(
        color: Colors.red,
        child: Center(
          child: _getListView(),
        ),
      ),
      Container(
        color: Colors.blue,
        child: Center(
          child: _getListView(),
        ),
      ),
    ];
  }

  ///底部的布局
  _getBottomViews() {
    return SizedBox(
        child: Row(
      children: [
        Expanded(
            child: GestureDetector(
          onTap: () {
            //不带动画的翻页
            _pageController.jumpToPage(0);

            //带动画的翻页
            /*_pageController.animateToPage(0,
                duration: const Duration(milliseconds: 100),
                curve: Curves.easeInOut);*/
          },
          child: Container(
            alignment: Alignment.center,
            height: 80,
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 20,
                  width: 20,
                  child: Image.asset(_index == 0
                      ? "assets/image/ai_chat_sel.png"
                      : "assets/image/ai_chat_unsel.png"),
                ),
                Text(
                  "11111",
                  style: TextStyle(
                      fontSize: 16,
                      color: _index == 0 ? Colors.black : Colors.black54),
                )
              ],
            ),
          ),
        )),
        Expanded(
            child: GestureDetector(
          onTap: () {
            //不带动画的翻页
            _pageController.jumpToPage(1);

            //带动画的翻页
            /*_pageController.animateToPage(1,
                duration: const Duration(milliseconds: 100),
                curve: Curves.easeInOut);*/
          },
          child: Container(
              alignment: Alignment.center,
              height: 80,
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height: 20,
                    width: 20,
                    child: Image.asset(_index == 1
                        ? "assets/image/ai_chat_sel.png"
                        : "assets/image/ai_chat_unsel.png"),
                  ),
                  Text(
                    "22222",
                    style: TextStyle(
                        fontSize: 16,
                        color: _index == 1 ? Colors.black : Colors.black54),
                  )
                ],
              )),
        )),
        Expanded(
            child: GestureDetector(
          onTap: () {
            //不带动画的翻页
            _pageController.jumpToPage(2);

            //带动画的翻页
            /*_pageController.animateToPage(2,
                duration: const Duration(milliseconds: 100),
                curve: Curves.easeInOut);*/
          },
          child: Container(
              alignment: Alignment.center,
              height: 80,
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height: 20,
                    width: 20,
                    child: Image.asset(_index == 2
                        ? "assets/image/ai_chat_sel.png"
                        : "assets/image/ai_chat_unsel.png"),
                  ),
                  Text(
                    "3333",
                    style: TextStyle(
                        fontSize: 16,
                        color: _index == 2 ? Colors.black : Colors.black54),
                  )
                ],
              )),
        )),
      ],
    ));
  }
}

_getListView() {
  return const _ItemPageWidget();
}

///pageview内的页面，如果要保持列表滑动位置等UI状态，需要使用
///AutomaticKeepAliveClientMixin来实现
class _ItemPageWidget extends StatefulWidget {
  const _ItemPageWidget({Key? key}) : super(key: key);

  @override
  _ItemPageWidgetState createState() => _ItemPageWidgetState();
}

class _ItemPageWidgetState extends State<_ItemPageWidget>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: 30,
      itemBuilder: (context, index) {
        return SizedBox(
          height: 80,
          child: Center(
            child: Text("item $index"),
          ),
        );
      },
      separatorBuilder: (BuildContext context, int index) {
        return const Divider(
          color: Colors.grey,
          height: 2,
        );
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  double get minExtent => 80; // 最小高度
  @override
  double get maxExtent => 80; // 最大高度

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    // 可以根据shrinkOffset或overlapsContent来动态调整内容
    return Container(
      color: Colors.blue,
      alignment: Alignment.center,
      child: Text(
        '我是自定义Header',
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    // 在这里可以根据需要决定是否需要重建header
    // 如果header的内容需要根据用户的滚动或其他条件变化，那么应该返回true
    return false;
  }
}
